/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xuidemo.slice;

import ohos.aafwk.ability.fraction.FractionManager;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.ComponentParent;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.agp.utils.Color;

import com.xuexiang.xui_lib.component.dialog.config.ConfigBean;
import com.xuexiang.xui_lib.component.dialog.interfaces.DialogListener;
import com.xuexiang.xui_lib.component.dialog.view.StyledDialog;
import com.xuexiang.xui_lib.component.guidview.GuideCaseQueue;
import com.xuexiang.xui_lib.component.guidview.GuideCaseView;
import com.xuexiang.xui_lib.component.imageview.RadiusImageView;
import com.xuexiang.xui_lib.util.PixelMapUtils;
import com.xuexiang.xuidemo.ResourceTable;
import com.xuexiang.xuidemo.ability.Aboutability;
import com.xuexiang.xuidemo.ability.QrCodeAbility;
import com.xuexiang.xuidemo.ability.SearchAbility;
import com.xuexiang.xuidemo.botnavigation.BottomBarInfo;
import com.xuexiang.xuidemo.botnavigation.BottomNavigationBar;
import com.xuexiang.xuidemo.db.SearchDatabase;
import com.xuexiang.xuidemo.db.SearchRecord;
import com.xuexiang.xuidemo.db.XUIDataBaseRepository;
import com.xuexiang.xuidemo.fraction.AssemblyFraction;
import com.xuexiang.xuidemo.fraction.ExpandFraction;
import com.xuexiang.xuidemo.fraction.ToolFraction;
import com.xuexiang.xuidemo.fractionstacklayout.AbilitySliceProvider;
import com.xuexiang.xuidemo.fractionstacklayout.BottomBarComponentProvider;
import com.xuexiang.xuidemo.fractionstacklayout.FractionBarComponent;
import com.xuexiang.xuidemo.util.AppCfig;
import com.xuexiang.xuidemo.util.DbUntil;
import com.xuexiang.xuidemo.util.JumpUtil;
import com.xuexiang.xuidemo.util.Shareprefance;
import com.xuexiang.xuidemo.util.SlidingRootNav;
import com.xuexiang.xuidemo.util.SlidingRootNavBuilder;
import com.xuexiang.xuidemo.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * slice
 *
 * @since 2021-03-18
 */
public class MainAbilitySlice extends BaseAbilitySlice implements AbilitySliceProvider, Component.ClickedListener {
    public final static String SHAREPREFANCE_FIRST_DRAWER_TAG = "first_drawer_tag";
    private FractionBarComponent mFractionBarComponent;
    private AbilitySliceProvider mAbilitySliceProvider;
    private Text maintext;
    private Image imgleft;
    private Image imgtworight;
    private Image imgright;
    /**
     * 底部导航栏
     */
    private BottomNavigationBar tabBottomLayout;
    /**
     * 底部导航栏的数据
     */
    private List<BottomBarInfo<?>> bottomInfoList;
    private int defaultColor;
    private int tintColor;
    private SlidingRootNav slidingRootNav;
    private Text textAssembly;
    private Text textTool;
    private Text textExpand;
    private Text textAbort;
    private Text textLogout;
    private Image imgSetting;
    private Image imgQrcode;
    private MainAbilitySlice mThis;
    private final float anFloat = 0.85f;
    private ConfigBean configBean = null;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        mThis = this;
        DbUntil.setDbService(XUIDataBaseRepository.getInstance()
            .getDataBase(this, SearchDatabase.class, SearchRecord.class)); // 初始化加载数据库
        mAbilitySliceProvider = this;
        defaultColor = mAbilitySliceProvider.getColor(ResourceTable.Color_default_color);
        tintColor = mAbilitySliceProvider.getColor(ResourceTable.Color_colorPrimary);
        bottomInfoList = new ArrayList<>();
        initview();
        initDrawer();
    }

    private void initview() {
        ToastUtil.showToastB0ttom(getContext(), " 登录成功!", new Color(AppCfig.two_black),
            ResourceTable.Media_ic_action_tick, 0);
        tabBottomLayout = (BottomNavigationBar) mAbilitySliceProvider.findComponentById(ResourceTable.Id_bottom_navigation_bar);
        maintext = (Text) findComponentById(ResourceTable.Id_Maintext);
        imgleft = (Image) findComponentById(ResourceTable.Id_imgleft);
        imgleft.setClickedListener(this::onClick);
        imgtworight = (Image) findComponentById(ResourceTable.Id_imgtworight);
        imgtworight.setClickedListener(this::onClick);
        imgright = (Image) findComponentById(ResourceTable.Id_imgright);
        imgright.setClickedListener(this::onClick);

        BottomBarInfo<Integer> favoriteInfo = new BottomBarInfo<>("组件",
            ResourceTable.Media_icon_tabbar_component,
            ResourceTable.Media_icon_tabbar_component_selected,
            defaultColor, tintColor);
        favoriteInfo.fraction = AssemblyFraction.class;

        BottomBarInfo<Integer> toolfration = new BottomBarInfo<>("工具",
            ResourceTable.Media_ico_gj72,
            ResourceTable.Media_ico_gjls72,
            defaultColor, tintColor);
        toolfration.fraction = ToolFraction.class;

        BottomBarInfo<Integer> expandfration = new BottomBarInfo<>("拓展",
            ResourceTable.Media_icon_tabbar_expand,
            ResourceTable.Media_icon_tabbar_expand_selected,
            defaultColor, tintColor);
        expandfration.fraction = ExpandFraction.class;

        bottomInfoList.add(favoriteInfo);
        bottomInfoList.add(toolfration);
        bottomInfoList.add(expandfration);

        tabBottomLayout.setBarBottomAlpha(anFloat);
        tabBottomLayout.initInfo(bottomInfoList);
        initFractionBarComponent();
        tabBottomLayout.addBarSelectedChangeListener((index, prevInfo, nextInfo) ->
            {
                mFractionBarComponent.setCurrentItem(index, maintext);
                setClickEffect(index);
            }
        );
        tabBottomLayout.defaultSelected(favoriteInfo); // 设置默认选中的条目，该方法一定要在最后调用
    }

    private void initFractionBarComponent() {

        FractionManager fractionManage = mAbilitySliceProvider.getFractionManager();
        BottomBarComponentProvider provider = new BottomBarComponentProvider(bottomInfoList, fractionManage);
        mFractionBarComponent = (FractionBarComponent) mAbilitySliceProvider.findComponentById(ResourceTable.Id_fraction_bar_component);
        mFractionBarComponent.setProvider(provider);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_imgleft:
                if (slidingRootNav.isMenuClosed()) {
                    slidingRootNav.openMenu();
                    showTextGuideView();
                } else
                    slidingRootNav.closeMenu();
                break;

            case ResourceTable.Id_imgtworight:
                JumpUtil.jumpToAbility(getContext(), SearchAbility.class);
                break;
            case ResourceTable.Id_imgright:
                JumpUtil.jumpToAbility(getContext(), Aboutability.class);
                break;
            case ResourceTable.Id_text_assembly:
                tabBottomLayout.onSelected(0);
                slidingRootNav.closeMenu();
                setClickEffect((Text) component);
                break;
            case ResourceTable.Id_text_tool:
                tabBottomLayout.onSelected(1);
                slidingRootNav.closeMenu();
                setClickEffect((Text) component);
                break;
            case ResourceTable.Id_text_expand:
                tabBottomLayout.onSelected(2);
                slidingRootNav.closeMenu();
                setClickEffect((Text) component);
                break;
            case ResourceTable.Id_text_abort:
                JumpUtil.jumpToAbility(getContext(), Aboutability.class);
                setClickEffect((Text) component);
                break;
            case ResourceTable.Id_text_logout:
                configBean = StyledDialog.buildTipAlert(getContext(), "是否确认退出？", "", "是", "否", new DialogListener() {
                    @Override
                    public void positiveButton() {
                        configBean.commonDialog.hide();
                        configBean.commonDialog = null;
                        setClickEffect((Text) component);
                        JumpUtil.jumpToAbility(getContext(), LoginAbility.class);
                        terminateAbility();
                    }

                    @Override
                    public void negativeButton() {
                        configBean.commonDialog.hide();
                        configBean.commonDialog = null;
                    }
                });
                configBean.commonDialog.show();
                break;
            default:
                break;
        }
    }

    /**
     * 加载的方法
     */
    public void initDrawer() {
        slidingRootNav = new SlidingRootNavBuilder(getAbility())
            .withArbitrarilyView(findComponentById(ResourceTable.Id_imgleft))
            .withMenuLayout(ResourceTable.Layout_menu_left_drawer)
            .inject();

        textAssembly = (Text) slidingRootNav.getLayout().findComponentById(ResourceTable.Id_text_assembly);
        textTool = (Text) slidingRootNav.getLayout().findComponentById(ResourceTable.Id_text_tool);
        textExpand = (Text) slidingRootNav.getLayout().findComponentById(ResourceTable.Id_text_expand);
        textAbort = (Text) slidingRootNav.getLayout().findComponentById(ResourceTable.Id_text_abort);
        textLogout = (Text) slidingRootNav.getLayout().findComponentById(ResourceTable.Id_text_logout);
        imgSetting = (Image) slidingRootNav.getLayout().findComponentById(ResourceTable.Id_img_setting);
        imgQrcode = (Image) slidingRootNav.getLayout().findComponentById(ResourceTable.Id_img_qrcode);
        RadiusImageView rivHead = (RadiusImageView) slidingRootNav.getLayout().findComponentById(ResourceTable.Id_riv_head);
        rivHead.setPixelMapToCircleImage(ResourceTable.Media_icon_avatar1);

        slidingRootNav.getLayout().findComponentById(ResourceTable.Id_img_qrcode).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                JumpUtil.jumpToAbility(getContext(), QrCodeAbility.class);
            }
        });

        textAssembly.setClickedListener(this);
        textTool.setClickedListener(this);
        textExpand.setClickedListener(this);
        textAbort.setClickedListener(this);
        textLogout.setClickedListener(this);

        setClickEffect(textAssembly);
    }

    public void setClickEffect(int index) {
        switch (index) {
            case 0:
                setClickEffect(textAssembly);
                break;
            case 1:
                setClickEffect(textTool);
                break;
            case 2:
                setClickEffect(textExpand);
                break;
            default:
                break;
        }
    }

    /**
     * 设置
     *
     * @param text 文本
     */
    public void setClickEffect(Text text) {
        if (textAssembly == null) {
            return;
        }
        textAssembly.setTextColor(new Color(Color.getIntColor("#223853")));
        textTool.setTextColor(new Color(Color.getIntColor("#223853")));
        textExpand.setTextColor(new Color(Color.getIntColor("#223853")));
        textAbort.setTextColor(new Color(Color.getIntColor("#223853")));
        textLogout.setTextColor(new Color(Color.getIntColor("#223853")));
        text.setTextColor(new Color(Color.getIntColor("#72B4D0")));

        textAssembly.setAroundElements(PixelMapUtils.getPixelMapElement(mThis, ResourceTable.Media_icon_tabbar_component),
            null, null, null);
        textTool.setAroundElements(PixelMapUtils.getPixelMapElement(mThis, ResourceTable.Media_icon_tabbar_util),
            null, null, null);
        textExpand.setAroundElements(PixelMapUtils.getPixelMapElement(mThis, ResourceTable.Media_icon_tabbar_expand),
            null, null, null);
        textAbort.setAroundElements(PixelMapUtils.getPixelMapElement(mThis, ResourceTable.Media_icon_tabbar_about),
            null, null, null);
        textLogout.setAroundElements(PixelMapUtils.getPixelMapElement(mThis, ResourceTable.Media_icon_tabbar_logout),
            null, null, null);

        switch (text.getId()) {
            case ResourceTable.Id_text_assembly:
                textAssembly.setAroundElements(PixelMapUtils.getPixelMapElement(mThis, ResourceTable.Media_icon_tabbar_component_selected),
                    null, null, null);
                break;
            case ResourceTable.Id_text_tool:
                textTool.setAroundElements(PixelMapUtils.getPixelMapElement(mThis, ResourceTable.Media_icon_tabbar_util_selected),
                    null, null, null);
                break;
            case ResourceTable.Id_text_expand:
                textExpand.setAroundElements(PixelMapUtils.getPixelMapElement(mThis, ResourceTable.Media_icon_tabbar_expand_selected),
                    null, null, null);
                break;
            case ResourceTable.Id_text_abort:
                break;
            case ResourceTable.Id_text_logout:
                break;
        }
    }


    /**
     * 显示文字引导
     */
    private void showTextGuideView() {
        Shareprefance shareprefance = new Shareprefance(mThis);
        shareprefance.initDB();

        ComponentParent componentParent = slidingRootNav.getLayout();
        while (true) {
            ComponentParent tmp = componentParent.getComponentParent();
            if (tmp == null) break;
            else componentParent = tmp;
        }

        if (!shareprefance.select(SHAREPREFANCE_FIRST_DRAWER_TAG)) {
            GuideCaseView guideStep1 = new GuideCaseView.Builder(getAbility())
                .title("点击进入，可切换主题样式哦～～")
                .titleSize(18, Text.TextSizeType.FP)
                .focusOn(imgSetting)
                .root((ComponentContainer) componentParent)
                .build();

            GuideCaseView guideStep2 = new GuideCaseView.Builder(getAbility())
                .title("点击进入，扫码关注哦～～")
                .titleSize(18, Text.TextSizeType.FP)
                .focusOn(imgQrcode)
                .root((ComponentContainer) componentParent)
                .build();

            new GuideCaseQueue()
                .add(guideStep1)
                .add(guideStep2)
                .show();

            shareprefance.insert(SHAREPREFANCE_FIRST_DRAWER_TAG, true);
        }
    }
}
